import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.odps.udf.UDF;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpliderTargetGoodsInfo extends UDF {
    /*public static void main(String[] args) {
        HttpClientAPI client = new HttpClientAPI();
        try {
            HttpResult httpResult = client.doGet("https://www.target.com/p/alaffia-everyday-coconut-baby-body-lotion-coconut-strawberry-16-fl-oz/-/A-53339205");
            SpliderTargetGoodsInfo target = new SpliderTargetGoodsInfo();
            target.evaluate(httpResult.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    public String evaluate(String html) {
        try {
            Map<String, Object> resultMap = new HashMap<>();
            if (StringUtils.isNotBlank(html)) {
                Document document = Jsoup.parse(html);
                //title volume
                Elements elementsByAttributeValue = document.getElementsByAttributeValue("data-test", "\"product-title\"");
                if (null != elementsByAttributeValue && elementsByAttributeValue.size() != 0) {
                    String titleInfo = elementsByAttributeValue.text();
                    System.out.println(titleInfo);
                    if (StringUtils.isNotBlank(titleInfo) && titleInfo.contains("-")) {
                        resultMap.put("title", titleInfo.substring(0, titleInfo.lastIndexOf("-")).trim());
                        resultMap.put("volume", titleInfo.substring(titleInfo.lastIndexOf("-") + 1).trim());
                    } else {
                        resultMap.put("title", titleInfo.trim());
                    }

                }
                //price
                Elements priceEles = document.getElementsByAttributeValue("data-test", "\"product-price\"");
                if (null != priceEles && priceEles.size() != 0) {
                    String price = priceEles.get(0).text();
                    resultMap.put("price", price.trim());
                }
                //level star
                Elements levelEles = document.getElementsByAttributeValue("data-test", "\"ratings\"");
                if (null != levelEles && levelEles.size() != 0) {
                    String[] levelArr = levelEles.get(0).text().split(" ");
                    resultMap.put("level", levelArr[0].trim());
                }

                //tag
                Elements tagEles = document.getElementsByAttributeValue("data-test", "\"wellnessBadgeOnly\"");
                if (null != tagEles && tagEles.size() != 0) {
                    StringBuffer sb = new StringBuffer();
                    for (Element tag: tagEles){
                        sb = sb.append(tag.text()).append("@!@");
                        System.out.println("tag :"+tag.text());
                    }
                    resultMap.put("tag", sb.substring(0,sb.lastIndexOf("@!@")));
                }


                //image
                Elements imgEles = document.getElementsByAttributeValue("data-test", "\"carousel-stage-wrapper\"");
                if (null != imgEles && imgEles.size() != 0) {
                    Elements imgClass = imgEles.get(0).getElementsByClass("slideDeckPicture");
                    Elements img1 = imgClass.get(0).getElementsByTag("img");
                    String img = img1.get(0).attr("src");
                    resultMap.put("img", img);
                }

                //description
                Element specAndDescript = document.getElementById("specAndDescript");
                if (null != specAndDescript) {
                    Elements div = specAndDescript.select("div > div > div > div");
                    Set<String> set = new LinkedHashSet<>();
                    for (Element e : div) {
                        set.add(e.text());
                    }
                    for (String a : set) {
                        if (a.contains(":")) {
                            String[] split = a.split(":");
                            resultMap.put(split[0], split[1]);
                        }
                    }

                    Elements descEles = specAndDescript.getElementsByClass("h-margin-v-default");
                    resultMap.put("description", descEles.text());
                }

                //获取强调内容
                Elements elementsByClass = document.getElementsByClass("h-margin-h-default h-margin-b-default h-display-flex");
                if (null != elementsByClass && elementsByClass.size() > 0) {
                    Elements li = elementsByClass.get(0).getElementsByTag("li");
                    if (null != li && li.size() > 0) {
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < li.size(); i++) {
                            sb = sb.append(i + 1 + ":").append(li.get(i).text()).append(".");
                        }
                        resultMap.put("highlights", sb.toString());
                    }
                }

                //ingredient
                Elements scriptEles = document.getElementsByTag("script");
                if (null != scriptEles && scriptEles.size() > 0) {
                    //window.__PRELOADED_STATE__
                    for (Element scriptEle : scriptEles)
                        try {
                            Pattern pattern = Pattern.compile("\"drugFacts\":(.*?),\"eligibility_rules\":");
                            Matcher matcher = pattern.matcher(scriptEle.toString());
                            if (matcher.find()) {
                                String group = matcher.group();
                                String s = group.replaceAll("\"drugFacts\":", "").replaceAll(",\"eligibility_rules\":", "");
                                System.out.println(s);
                                JSONObject jsonObject = JSONObject.parseObject(s);
                                //活性成分
                                JSONObject inactiveIngredients = jsonObject.getJSONObject("inactiveIngredients");
                                JSONObject activeIngredients = jsonObject.getJSONObject("activeIngredients");
                                if (null != inactiveIngredients && inactiveIngredients.size() > 0) {
                                    String ingredients = inactiveIngredients.getString("description");

                                    if (null != activeIngredients && StringUtils.isNotBlank(activeIngredients.getString("description"))) {
                                        ingredients = ingredients + activeIngredients.getString("description");
                                    }

                                    resultMap.put("activeIngredient", ingredients);
                                }
                                //其他成分
                                resultMap.put("otherIngredient", jsonObject.getJSONArray("other_directions"));

                                //功效purpose
                                JSONObject purpose = jsonObject.getJSONObject("purpose");
                                if (null != purpose && purpose.size() > 0) {
                                    String description = purpose.getString("description");
                                    resultMap.put("purpose", description);
                                }

                            }

                        } catch (JSONException e) {
                            continue;
                        }
                }
            }
            System.out.println(JSON.toJSONString(resultMap));

            return JSON.toJSONString(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
